<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="get">get</button>
    <button class="post">post</button>
</body>

<script>
    var getbtn = document.getElementsByClassName('get')[0]
    var postBtn = document.getElementsByClassName('post')[0]
    getbtn.onclick = function () {
        var wd = "";  // 搜素的关键词 默认请求所有
        var col = "id"; // 排序的列名 默认id排序
        var type = "asc"; // 排序的方式 默认升序
        var page = 1;  // 页码 默认显示第一页
        var size = 10; // 每页显示多少条 默认
        ajax({
            type: 'get',
            dataType: 'json',
            data: {
                wd: "",
                col: "id",
                type: "asc",
                page: 1,
                size: 10
            },
            success: function (data) { console.log('请求成功', data); },
            url: 'http://43.138.81.225/demo/php/searchGoodsOrderLimit.php'
        })
    }


    postBtn.onclick = function () {
        var user = "asasdd123123";
        var pwd = "123123";
        var phone = "17386153331";
        var email = "143332@qq.com";

        // debugger;
        ajax({
            type: "post",
            url: "http://43.138.81.225/demo/php/register.php",
            data: {
                user,
                pwd,
                phone,
                email,
            },
            async: true,
            dataType: "json",
            success: function (res) {
                console.log("请求成功", res);
            }

        })
    }


    function ajax(ajaxObject) {
        var { type = 'get', url, data = '', async = true, dataType = "text", success } = ajaxObject
        var xhr = new XMLHttpRequest()
        if (typeof data == 'object') {
            var dataList = []
            for (var key in data) {
                dataList.push(key + '=' + data[key])
            }
            data = dataList.join('&')
        }
        if (type.toLowerCase() == 'get') {
            xhr.open('get', data ? url + '?' + data : url, async)
            xhr.send()
        } else if (type.toLowerCase() == 'post') {
            xhr.open('post', url, async)
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
            xhr.send(data)
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var res = xhr.responseText
                if (dataType == 'json') {
                    res = JSON.parse(res)
                }
                if (success && typeof success === "function") {
                    success(res)
                    // console.log(res);
                }
            }
        }
    }



</script>

</html>